package com.cxdr.awsips.distribute.rule;

import java.text.ParseException;
import java.util.Date;

import org.apache.commons.lang3.time.DateUtils;
import org.apache.log4j.Logger;

import com.cxdr.awsips.common.logger.LogFactory;

/**
 * 时间分发策略
 * 
 * @author pugang
 * 
 */
public class TimeRule {
	private static Logger logger = LogFactory.makeNewLogger(TimeRule.class);
	private String id;
	private String filter_type;
	public String begin_time;
	public String end_time;
	private Date begin_time_date;
	private Date end_time_date;
	public static final String INCLUDE_TYPE = "include";
	public static final String OUT_TYPE = "out";
	public static final String DATE_PATTEN = "yyyy-MM-dd HH:mm:ss";

	public TimeRule() {

	}

	public TimeRule(String filter, String begin_time, String end_time) {
		setFilter_type(filter);
		setBegin_time(begin_time);
		setEnd_time(end_time);
	}

	public TimeRule(String id, String filter, String begin_time, String end_time) {
		setId(id);
		setFilter_type(filter);
		setBegin_time(begin_time);
		setEnd_time(end_time);
	}

	public boolean accept(Date fileTime) {
		boolean accept = false;
		if (INCLUDE_TYPE.equals(filter_type)) {
			accept = (fileTime.getTime() >= begin_time_date.getTime() && fileTime
					.getTime() <= end_time_date.getTime());
		} else if (OUT_TYPE.equals(filter_type)) {
			accept = (fileTime.getTime() < begin_time_date.getTime() || fileTime
					.getTime() > end_time_date.getTime());
		}
		return accept;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getFilter_type() {
		return filter_type;
	}

	public void setFilter_type(String filter_type) {
		if (!INCLUDE_TYPE.equals(filter_type) && !OUT_TYPE.equals(filter_type)) {
			throw new RuntimeException("filter_type should be " + INCLUDE_TYPE
					+ " or " + OUT_TYPE + " !");
		}
		this.filter_type = filter_type;
	}

	public static void main(String[] args) throws ParseException {
		 TimeRule role = new TimeRule(FileNameRule.INCLUDE_TYPE,"2011-12-24 00:00:00","2012-02-10 00:00:00");
		 Date time = DateUtils.parseDate("2011-12-24 00:00:00", DATE_PATTEN);
		 System.out.println(role.accept(time));
	}

	public String getBegin_time() {
		return begin_time;
	}

	public void setBegin_time(String begin_time) {
		begin_time_date = parseTime(begin_time);
		this.begin_time = begin_time;
	}

	public String getEnd_time() {
		return end_time;
	}

	public void setEnd_time(String end_time) {
		end_time_date = parseTime(end_time);
		this.end_time = end_time;
	}

	private Date parseTime(String time) {
		Date date;
		try {
			date = DateUtils.parseDate(time, DATE_PATTEN);
		} catch (ParseException e) {
			logger.error("parseTime error", e);
			e.printStackTrace();
			throw new RuntimeException(e);
		}
		return date;
	}
	
	public String desc(){
		return "filter_type："+filter_type+" beign："+begin_time+" ; end:"+end_time;
	}
}
